﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using System.Collections;

namespace WebService
{
    public class CCWebService : ICurrencyConverterService
    {
        private Hashtable curDB;

        public CCWebService()
        {
            curDB = new Hashtable();

            XmlTextReader reader = new XmlTextReader("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
            while (reader.Read())
            {
                XmlNodeType nType = reader.NodeType;
                if (nType == XmlNodeType.Element)
                {
                    if (reader.Name.Equals("Cube") && reader.AttributeCount == 2)
                    {
                        string val = reader[1].Replace('.', ',');
                        curDB.Add(reader[0], Convert.ToSingle(val));
                    }
                }
            }
            curDB.Add("EUR", 1.0f);
        }
        public float calculate(string curFrom, string curTo, float amount) {
            if (curFrom != null && curTo != null && curDB.Contains(curFrom) && curDB.Contains(curTo))
            {
                if (curFrom.Equals("EUR"))
                {
                    return amount * (float)curDB[curTo];
                }
                else if (curTo.Equals("EUR"))
                {
                    return amount / (float)curDB[curFrom];
                }
                else
                {
                    float eur = amount / (float)curDB[curFrom];
                    return eur * (float)curDB[curTo];
                }
            }
            else
            {
                return 0;
            }
        }
        public string[] listAllCurrencies()
        {

            string[] list = new string[curDB.Count];
            curDB.Keys.CopyTo(list, 0);
            return list;
        }
    }
}
